package recycle.controller;

import io.vertx.core.MultiMap;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import recycle.common.ResponseHandler;
import recycle.pojo.User;
import recycle.service.UserService;

public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    public void setupRoutes(Router router) {
        router.get("/users/exist/:phone").handler(this::exist);
        router.post("/users/register").handler(this::register);
        router.post("/users/login").handler(this::login);

        router.post("/users/create").handler(this::create);
        router.delete("/users/delete/:id").handler(this::delete);
        router.put("/users/update").handler(this::update);
        router.get("/users/details/:id").handler(this::details);
        router.get("/users/details").handler(this::detailsByPhone);
        router.post("/users/list").handler(this::list);
    }


    private void login(RoutingContext ctx) {
        User user = ctx.body().asPojo(User.class);
        userService.login(user).onComplete(ResponseHandler.handle(ctx));
    }


    private void register(RoutingContext ctx) {
        User user = ctx.body().asPojo(User.class);
        userService.create(user).onComplete(ResponseHandler.handle(ctx));
    }

    private void exist(RoutingContext ctx) {
        String phone = ctx.pathParam("phone");
        userService.exist(phone).onComplete(ResponseHandler.handle(ctx));
    }

    private void create(RoutingContext ctx) {
        User user = ctx.body().asPojo(User.class);
        userService.create(user).onComplete(ResponseHandler.handle(ctx));
    }

    private void list(RoutingContext ctx) {
        User user = ctx.body().asPojo(User.class);
        MultiMap params = ctx.request().params();
        Integer pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum")) : 1;
        Integer pageSize = params.get("pageSize")!= null ? Integer.parseInt(params.get("pageSize")) : 10;
        userService.list(user,pageNum,pageSize).onComplete(ResponseHandler.handle(ctx));
    }

    private void details(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        userService.details(id).onComplete(ResponseHandler.handle(ctx));
    }
    private void detailsByPhone(RoutingContext ctx) {
        String phone = ctx.request().getParam("phone");
        userService.detailsByUsername(phone).onComplete(ResponseHandler.handle(ctx));
    }


    private void update(RoutingContext ctx) {
        User user = ctx.body().asPojo(User.class);
        userService.update(user).onComplete(ResponseHandler.handle(ctx));
    }

    private void delete(RoutingContext ctx) {
        Long id = Long.parseLong(ctx.pathParam("id"));
        userService.delete(id).onComplete(ResponseHandler.handle(ctx));
    }
}